package com.zbc.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zbc.annotations.AuthCheck;
import com.zbc.constants.UserConstant;
import com.zbc.domain.common.DeleteRequest;
import com.zbc.domain.common.Result;
import com.zbc.domain.entity.Picture;
import com.zbc.domain.entity.User;
import com.zbc.domain.request.picture.*;
import com.zbc.domain.vo.PictureTagCategory;
import com.zbc.domain.vo.PictureVO;
import com.zbc.enums.ErrorCode;
import com.zbc.enums.PictureReviewStatusEnum;
import com.zbc.exception.BusinessException;
import com.zbc.service.PictureService;
import com.zbc.service.UserService;
import com.zbc.utils.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2025/9/2 16:09
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "图片模块")
public class PictureController {
    private final PictureService pictureService;
    private final UserService userService;
    private long pageSize;

    /**
     * 上传图片
     *
     * @param multipartFile 上传图片
     * @param uploadRequest 上传参数
     * @param request       当前登录用户
     * @return 图片信息(脱敏)
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传图片")
    @ApiOperationSupport(order = 1)
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile, PictureUploadRequest uploadRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(multipartFile), ErrorCode.PARAMS_ERROR, "上传文件不能为空");
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, uploadRequest, loginUser);
        return Result.success(pictureVO);
    }

    /**
     * 删除图片
     *
     * @param deleteRequest id
     * @param request       当前登录用户
     * @return 删除结果
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除图片")
    public Result<Boolean> deletePictureById(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(), loginUser);
        return Result.success(true);
    }

    /**
     * 更新图片
     *
     * @param pictureUpdateRequest 图片更新请求
     * @param request              当前登录用户
     * @return 更新结果
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新图片 (管理员)")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        List<String> list = pictureUpdateRequest.getTags();
        String jsonStr = JSONUtil.toJsonStr(list);
        picture.setTags(jsonStr);
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        Picture oldPicture = pictureService.getById(pictureUpdateRequest.getId());
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 填充审核参数
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);
        // 执行更新
        boolean updated = pictureService.updateById(picture);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 分页获取图片列表
     *
     * @param request 查询条件
     * @return 图片列表
     */
    @PostMapping("/list/page")
    @ApiOperation(value = "分页获取图片 (管理员)")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest request) {
        long current = request.getCurrent();
        long pageSize = request.getPageSize();
        Page<Picture> picturePage = new Page<>(current, pageSize);
        QueryWrapper<Picture> wrapper = pictureService.getQueryWrapper(request);
        Page<Picture> page = pictureService.page(picturePage, wrapper);
        return Result.success(page);
    }

    /**
     * 分页获取图片列表
     *
     * @param queryRequest 查询条件
     * @return 图片列表
     */
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取图片")
    public Result<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest queryRequest) {
        long current = queryRequest.getCurrent();
        long pageSize = queryRequest.getPageSize();
        // 限制条数
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        Page<Picture> picturePage = new Page<>(current, pageSize);
        QueryWrapper<Picture> wrapper = pictureService.getQueryWrapper(queryRequest);
        Page<Picture> page = pictureService.page(picturePage, wrapper);
        // 保证用户只能看到过审的图片
        queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(page);
        return Result.success(pictureVOPage);
    }

    /**
     * 根据 id 搜索图片
     *
     * @param id      图片 id
     * @return 图片信息
     */
    @GetMapping("/get")
    @ApiOperation(value = "根据 id 搜索图片 (管理员)")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Picture> getPictureById(@RequestParam("id") long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查询图片是否存在
        Picture picture = pictureService.getById(id);
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        return Result.success(picture);
    }

    /**
     * 根据 id 搜索图片
     *
     * @param id 图片 id
     * @return 图片信息
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据 id 搜索图片")
    public Result<PictureVO> getPictureVOById(@RequestParam("id") long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查询图片是否存在
        Picture picture = pictureService.getById(id);
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        }
        PictureVO pictureVO = pictureService.getPictureVOWithUserVO(picture);
        return Result.success(pictureVO);
    }

    /**
     * 编辑图片信息
     *
     * @param pictureEditRequest 图片编辑请求
     * @param request            当前登录用户
     * @return 编辑结果
     */
    @PostMapping("/edit")
    @ApiOperation(value = "编辑图片")
    public Result<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, currentUser);
        return Result.success(true);
    }

    /**
     * 获取预制标签和分类
     *
     * @return 预制标签和分类
     */
    @GetMapping("/tag_category")
    public Result<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "艺术", "校园", "背景", "创意", "游戏", "动漫", "其他");
        List<String> categoryList = Arrays.asList("电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return Result.success(pictureTagCategory);
    }

    /**
     * 图片审核
     *
     * @param reviewRequest 图片审核请求
     * @param request       当前登录用户
     * @return 图片审核结果
     */
    @PostMapping("/review")
    @ApiOperation(value = "图片审核 (管理员)")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> dePictureReview(@RequestBody PictureReviewRequest reviewRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(reviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.dePictureReview(reviewRequest, loginUser);
        return Result.success(true);
    }
}
